<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;
use app\common\service\TxEss;
use app\admin\model\Company;
use app\admin\model\contract\Record as ContractRecord;

/**
 * 员工管理
 *
 * @icon fa fa-circle-o
 */
class Staff extends Backend
{

    /**
     * Staff模型对象
     * @var \app\admin\model\Staff
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Staff;
        $this->view->assign("genderList", $this->model->getGenderList());
    }

    // 根据公司id获取templateId
    public function getTemplateIdListByCompanyId($company_id) {
        $datalist = [
            // 上海申瑞人力资源有限公司
            3=>[
                ['name'=>'劳动合同', 'value'=>'yDCYLUU5v3nc1jUqzfmxuBhJ6pT3jy8u', 'doc'=>'/uploads/salary/pdf/劳动合同.docx'],
                ['name'=>'中药厂合同', 'value'=>'yDtCrUUl7b0a19Uui9ulrvxYij2Yhn6j'],
                ['name'=>'退休返聘协议', 'value'=>'yDtCrUUl7bvfqtUucGHGoG3jGmQvsw1O'],
                ['name'=>'厨保洁机场', 'value'=>'yDtCrUUl7unz64UEc3ZwnRueWCoLDPCk'],
                ['name'=>'鑫小时工聘用协议', 'value'=>'yDtCrUUl7uhfniUucGHGoEQohYMDr24m'],
            ],
            // 安徽酷驰人力资源有限公司
            4=>[
                ['name'=>'劳动合同', 'value'=>'yDtCrUUl7uq6e3UggQaLRSAYWnzpF2JC'],
            ],
            // 江西省申瑞人力资源有限公司
            5=>[]
        ];

        $result = isset($datalist[$company_id]) ? $datalist[$company_id] : [];
        return json($result);
    }

    //合同管理
    public function contract($ids = null)
    {
        $agent = 0;
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($row['templateId'] == 'yDtCrUUl7uq6e3UggQaLRSAYWnzpF2JC') {
            $agent = 1;
        }

        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }

        $companyInfo = Company::where('id', $row['company_id'])->find();
        $operatorUserId = $companyInfo['operatorUserId']; //经办人Id
        $serverSignSealId = $companyInfo['serverSignSealId']; //企业印章Id

        $contract_status_text = '';
        // 如果有合同了，查询合同详情
        if ($row['flowid']) {
            $txEss = new TxEss($operatorUserId, $serverSignSealId);
            $contractInfo = $txEss->detailContract([$row['flowid']], $agent);
            if ($contractInfo['code']) {
                // $this->error('“查询合同流程的详情信息”出错：'.$contractInfo['msg']);
                \think\Log::info('staff表id为'.$row['id'].',flowid为'.$row['flowid'].'的数据“查询合同流程的详情信息”出错：'.$contractInfo['msg']);
            } else {
                $contract_status = $contractInfo['data']['FlowDetailInfos'][0]->FlowStatus;
                // 更新合同状态
                $this->model::where('id', $ids)->update(['contract_status'=>$contract_status]);
                $contract_status_text = $txEss->getContractStatus($contract_status, $agent);
            }
            unset($txEss);
        }

        // 查询用户合同记录(代签章)
        $contractRecordList = ContractRecord::where('staff_id', $row['id'])->where('templateId', 'yDtCrUUl7uq6e3UggQaLRSAYWnzpF2JC')->select();
        if ($contractRecordList) {
            $flowid_arr = [];
            foreach ($contractRecordList as $list) {
                $flowid_arr[] = $list['flowid'];
            }
            $nowCompany = Company::where('name', '安徽酷驰人力资源有限公司')->find();
            if (empty($nowCompany)) {
                $this->error('安徽酷驰人力资源有限公司 不存在');
            }
            $txEss = new TxEss($nowCompany['operatorUserId'], $nowCompany['serverSignSealId']);
            $contractInfo = $txEss->detailContract($flowid_arr, 1);
            if ($contractInfo['code']) {
                $this->error('查询用户合同记录(代签章)“查询合同流程的详情信息”出错：'.$contractInfo['msg']);
                // \think\Log::info('contract_record表,flowid为'.$row['flowid'].'的数据“查询合同流程的详情信息”出错：'.$contractInfo['msg']);
            } else {
                // 循环更新
                foreach ($contractInfo['data']['FlowDetailInfos'] as $key => $list) {
                    $res = ContractRecord::where('flowid', $list->FlowId)->update(['contract_status'=>$list->FlowStatus, 'flowinfo'=>serialize($list), 'updatetime'=>time()]);
                    if (empty($res)) {
                        $this->error('FlowId:'.$list->FlowId.'，更新合同状态为'.$list->FlowStatus.'失败');
                    }
                }
            }

            unset($txEss);
        }
        // 查询用户合同记录(非代签章)
        $contractRecordList = ContractRecord::where('staff_id', $row['id'])->where('templateId', '<>','yDtCrUUl7uq6e3UggQaLRSAYWnzpF2JC')->select();
        if ($contractRecordList) {
            $flowid_arr = [];
            foreach ($contractRecordList as $list) {
                $flowid_arr[] = $list['flowid'];
            }

            $txEss = new TxEss($operatorUserId, $serverSignSealId);
            $contractInfo = $txEss->detailContract($flowid_arr, 0);
            if ($contractInfo['code']) {
                $this->error('查询用户合同记录(非代签章)“查询合同流程的详情信息”出错：'.$contractInfo['msg']);
                // \think\Log::info('contract_record表,flowid为'.$row['flowid'].'的数据“查询合同流程的详情信息”出错：'.$contractInfo['msg']);
            } else {
                // 循环更新
                foreach ($contractInfo['data']['FlowDetailInfos'] as $key => $list) {
                    $res = ContractRecord::where('flowid', $list->FlowId)->update(['contract_status'=>$list->FlowStatus, 'flowinfo'=>serialize($list), 'updatetime'=>time()]);
                    if (empty($res)) {
                        $this->error('FlowId:'.$list->FlowId.'，更新合同状态为'.$list->FlowStatus.'失败');
                    }
                }
            }

            unset($txEss);
        }

        $contractRecordList = ContractRecord::where('staff_id', $row['id'])->order('id', 'desc')->select();
        if ($contractRecordList) {
            $txEss = new TxEss($operatorUserId, $serverSignSealId);
            foreach ($contractRecordList as $key=>$list) {
                $contractRecordList[$key]['contract_status_text2'] = $txEss->getContractStatus($list['contract_status']);
            }
            unset($txEss);
        }

        if (false === $this->request->isPost()) {

            // 查询公司列表
            $companyList = Company::where('id', '>', 0)->order('weigh', 'desc')->select();

            if ($row['other_data']) {
                $row['other_data'] = unserialize($row['other_data']);
            }

            $this->view->assign('companyList', $companyList);
            $this->view->assign('row', $row);
            $this->view->assign('contract_status_text', $contract_status_text);
            $this->view->assign('contractRecordList', $contractRecordList);
            return $this->view->fetch();
        }

        $agent = 0;
        // 提交生成电子合同
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        // 验证身份证
        if (!checkIdCard($params['idcard'])) {
            $this->error('身份证号不合法');
        }

        $exists = $this->model::where(['mobile'=>$params['mobile'], 'id'=>['<>', $ids]])->find();
        if (!empty($exists)) {
            $this->error('手机号'.$params['mobile'].'已存在，不能添加重复的手机号数据');
        }

        $exists = $this->model::where(['idcard'=>$params['idcard'], 'id'=>['<>', $ids]])->find();
        if (!empty($exists)) {
            $this->error('身份证号'.$params['idcard'].'已存在，不能添加重复的身份证号数据');
        }

        // 准备数据
        $gender = $params['gender'] == 1 ? '男' : '女';
        $contract_start_date = explode('-', $params['contract_start_date']);
        $contract_end_date = explode('-', $params['contract_end_date']);
        $internship_start_date = explode('-', $params['internship_start_date']);
        $internship_end_date = explode('-', $params['internship_end_date']);

        // 判断选择的哪个合同
        $templateId = $params['templateId'];
        if (empty($templateId)) {
            $this->error('请选择合同');
        }

        $FormFields = [];

        if ($templateId == 'yDCYLUU5v3nc1jUqzfmxuBhJ6pT3jy8u') {
            $FormFields = [
                ['ComponentName'=>'姓名', "ComponentValue"=>$params['name']],
                ['ComponentName'=>'性别', "ComponentValue"=>$gender],
                ['ComponentName'=>'联系电话', "ComponentValue"=>$params['mobile']],
                ['ComponentName'=>'证件号码', "ComponentValue"=>$params['idcard']],
                ['ComponentName'=>'户籍地址', "ComponentValue"=>$params['permanentAddress']],
                ['ComponentName'=>'现居住地址', "ComponentValue"=>$params['currentAddress']],
                ['ComponentName'=>'紧急联系人姓名', "ComponentValue"=>$params['urgent_name']],
                ['ComponentName'=>'紧急联系人电话', "ComponentValue"=>$params['urgent_mobile']],
                ['ComponentName'=>'合同期限年', "ComponentValue"=>$contract_start_date[0]],
                ['ComponentName'=>'合同期限月', "ComponentValue"=>$contract_start_date[1]],
                ['ComponentName'=>'合同期限日', "ComponentValue"=>$contract_start_date[2]],
                ['ComponentName'=>'合同期限年2', "ComponentValue"=>$contract_end_date[0]],
                ['ComponentName'=>'合同期限月2', "ComponentValue"=>$contract_end_date[1]],
                ['ComponentName'=>'合同期限日2', "ComponentValue"=>$contract_end_date[2]],
                ['ComponentName'=>'合同试用期几个月', "ComponentValue"=>$params['internship_months']],
                ['ComponentName'=>'合同试用期年', "ComponentValue"=>$internship_start_date[0]],
                ['ComponentName'=>'合同试用期月', "ComponentValue"=>$internship_start_date[1]],
                ['ComponentName'=>'合同试用期日', "ComponentValue"=>$internship_start_date[2]],
                ['ComponentName'=>'合同试用期年2', "ComponentValue"=>$internship_end_date[0]],
                ['ComponentName'=>'合同试用期月2', "ComponentValue"=>$internship_end_date[1]],
                ['ComponentName'=>'合同试用期日2', "ComponentValue"=>$internship_end_date[2]],
            ];
        }

        /**
         * 中药厂合同
         * yDtCrUUl7b0a19Uui9ulrvxYij2Yhn6j
         *
         * 姓名、性别、联系电话、在沪居住地址、紧急联系人姓名、紧急联系人电话、合同期限年、合同期限月、合同期限日、合同期限年2、合同期限月2、合同期限日2、证件号码、户籍地址
         * ***/
        if ($templateId == 'yDtCrUUl7b0a19Uui9ulrvxYij2Yhn6j') {
            $FormFields = [
                ['ComponentName'=>'姓名', "ComponentValue"=>$params['name']],
                ['ComponentName'=>'性别', "ComponentValue"=>$gender],
                ['ComponentName'=>'联系电话', "ComponentValue"=>$params['mobile']],
                ['ComponentName'=>'在沪居住地址', "ComponentValue"=>$params['currentAddress']],
                ['ComponentName'=>'紧急联系人姓名', "ComponentValue"=>$params['urgent_name']],
                ['ComponentName'=>'紧急联系人电话', "ComponentValue"=>$params['urgent_mobile']],
                ['ComponentName'=>'合同期限年', "ComponentValue"=>$contract_start_date[0]],
                ['ComponentName'=>'合同期限月', "ComponentValue"=>$contract_start_date[1]],
                ['ComponentName'=>'合同期限日', "ComponentValue"=>$contract_start_date[2]],
                ['ComponentName'=>'合同期限年2', "ComponentValue"=>$contract_end_date[0]],
                ['ComponentName'=>'合同期限月2', "ComponentValue"=>$contract_end_date[1]],
                ['ComponentName'=>'合同期限日2', "ComponentValue"=>$contract_end_date[2]],
                ['ComponentName'=>'证件号码', "ComponentValue"=>$params['idcard']],
                ['ComponentName'=>'户籍地址', "ComponentValue"=>$params['permanentAddress']],
            ];
        }

        /**
         * 退休返聘协议
         * yDtCrUUl7bvfqtUucGHGoG3jGmQvsw1O
         *
         * 协议编号
         * 姓名
         * 再次输入姓名
         * 三次输入姓名
         * 性别
         * 证件号
         * 户籍地址
         * 现居住地址
         * 联系电话
         * 紧急联系人姓名及电话
         * 合同期限几年
         * 合同期限年
         * 合同期限月
         * 合同期限日
         * 合同期限年2
         * 合同期限月2
         * 合同期限日2
         * 月工资
         * 每月几号发工资
         * ***/
        if ($templateId == 'yDtCrUUl7bvfqtUucGHGoG3jGmQvsw1O') {
            $FormFields = [
                ['ComponentName'=>'协议编号', "ComponentValue"=>$params['other_data']['协议编号']], //改成活的
                ['ComponentName'=>'合同期限几年', "ComponentValue"=>$params['other_data']['合同期限几年']], //改成活的
                ['ComponentName'=>'月工资', "ComponentValue"=>$params['other_data']['月工资']], //改成活的
                ['ComponentName'=>'每月几号发工资', "ComponentValue"=>$params['other_data']['每月几号发工资']], //改成活的
                ['ComponentName'=>'姓名', "ComponentValue"=>$params['name']],
                ['ComponentName'=>'再次输入姓名', "ComponentValue"=>$params['name']],
                ['ComponentName'=>'三次输入姓名', "ComponentValue"=>$params['name']],
                ['ComponentName'=>'性别', "ComponentValue"=>$gender],
                ['ComponentName'=>'证件号', "ComponentValue"=>$params['idcard']],
                ['ComponentName'=>'户籍地址', "ComponentValue"=>$params['permanentAddress']],
                ['ComponentName'=>'现居住地址', "ComponentValue"=>$params['currentAddress']],
                ['ComponentName'=>'联系电话', "ComponentValue"=>$params['mobile']],
                ['ComponentName'=>'紧急联系人姓名及电话', "ComponentValue"=>$params['urgent_name'].' '.$params['urgent_mobile']],
                ['ComponentName'=>'合同期限年', "ComponentValue"=>$contract_start_date[0]],
                ['ComponentName'=>'合同期限月', "ComponentValue"=>$contract_start_date[1]],
                ['ComponentName'=>'合同期限日', "ComponentValue"=>$contract_start_date[2]],
                ['ComponentName'=>'合同期限年2', "ComponentValue"=>$contract_end_date[0]],
                ['ComponentName'=>'合同期限月2', "ComponentValue"=>$contract_end_date[1]],
                ['ComponentName'=>'合同期限日2', "ComponentValue"=>$contract_end_date[2]],
            ];
        }

        /**
         * 厨保洁机场
         * yDtCrUUl7unz64UEc3ZwnRueWCoLDPCk
         *
         * 姓名
         * 证件号
         * 联系电话
         * 现居住地址
         * 紧急联系人姓名
         * 紧急联系人电话
         * 合同期限几年
         * 合同期限年
         * 合同期限月
         * 合同期限日
         * 合同期限年2
         * 合同期限月2
         * 合同期限日2
         * 合同试用期几个月
         * 合同试用期年
         * 合同试用期月
         * 合同试用期日
         * 合同试用期年2
         * 合同试用期月2
         * 合同试用期日2
         * 月工资
         * 试用期月工资
         * 每月几号发工资
         * */
        if ($templateId == 'yDtCrUUl7unz64UEc3ZwnRueWCoLDPCk') {
            $FormFields = [
                ['ComponentName'=>'合同期限几年', "ComponentValue"=>$params['other_data']['合同期限几年']], //改成活的
                ['ComponentName'=>'月工资', "ComponentValue"=>$params['other_data']['月工资']], //改成活的
                ['ComponentName'=>'试用期月工资', "ComponentValue"=>$params['other_data']['试用期月工资']], //改成活的
                ['ComponentName'=>'每月几号发工资', "ComponentValue"=>$params['other_data']['每月几号发工资']], //改成活的
                ['ComponentName'=>'合同试用期几个月', "ComponentValue"=>$params['internship_months']],
                ['ComponentName'=>'姓名', "ComponentValue"=>$params['name']],
                ['ComponentName'=>'证件号', "ComponentValue"=>$params['idcard']],
                ['ComponentName'=>'联系电话', "ComponentValue"=>$params['mobile']],
                ['ComponentName'=>'现居住地址', "ComponentValue"=>$params['currentAddress']],
                ['ComponentName'=>'紧急联系人姓名', "ComponentValue"=>$params['urgent_name']],
                ['ComponentName'=>'紧急联系人电话', "ComponentValue"=>$params['urgent_mobile']],
                ['ComponentName'=>'合同期限年', "ComponentValue"=>$contract_start_date[0]],
                ['ComponentName'=>'合同期限月', "ComponentValue"=>$contract_start_date[1]],
                ['ComponentName'=>'合同期限日', "ComponentValue"=>$contract_start_date[2]],
                ['ComponentName'=>'合同期限年2', "ComponentValue"=>$contract_end_date[0]],
                ['ComponentName'=>'合同期限月2', "ComponentValue"=>$contract_end_date[1]],
                ['ComponentName'=>'合同期限日2', "ComponentValue"=>$contract_end_date[2]],
                ['ComponentName'=>'合同试用期年', "ComponentValue"=>$internship_start_date[0]],
                ['ComponentName'=>'合同试用期月', "ComponentValue"=>$internship_start_date[1]],
                ['ComponentName'=>'合同试用期日', "ComponentValue"=>$internship_start_date[2]],
                ['ComponentName'=>'合同试用期年2', "ComponentValue"=>$internship_end_date[0]],
                ['ComponentName'=>'合同试用期月2', "ComponentValue"=>$internship_end_date[1]],
                ['ComponentName'=>'合同试用期日2', "ComponentValue"=>$internship_end_date[2]],
            ];
        }

        /**
         * 金鑫小时工聘用协议
         * yDtCrUUl7uhfniUucGHGoEQohYMDr24m
         *
         * 姓名
         * 性别
         * 证件号
         * 现居住地址
         * 联系电话
         * 户籍地址
         * 紧急联系人姓名
         * 紧急联系人电话
         * 合同期限年
         * 合同期限月
         * 合同期限日
         * 合同期限年2
         * 合同期限月2
         * 合同期限日2
         * */
        if ($templateId == 'yDtCrUUl7uhfniUucGHGoEQohYMDr24m') {
            $FormFields = [
                ['ComponentName'=>'姓名', "ComponentValue"=>$params['name']],
                ['ComponentName'=>'性别', "ComponentValue"=>$gender],
                ['ComponentName'=>'证件号', "ComponentValue"=>$params['idcard']],
                ['ComponentName'=>'现居住地址', "ComponentValue"=>$params['currentAddress']],
                ['ComponentName'=>'联系电话', "ComponentValue"=>$params['mobile']],
                ['ComponentName'=>'户籍地址', "ComponentValue"=>$params['permanentAddress']],
                ['ComponentName'=>'紧急联系人姓名', "ComponentValue"=>$params['urgent_name']],
                ['ComponentName'=>'紧急联系人电话', "ComponentValue"=>$params['urgent_mobile']],
                ['ComponentName'=>'合同期限年', "ComponentValue"=>$contract_start_date[0]],
                ['ComponentName'=>'合同期限月', "ComponentValue"=>$contract_start_date[1]],
                ['ComponentName'=>'合同期限日', "ComponentValue"=>$contract_start_date[2]],
                ['ComponentName'=>'合同期限年2', "ComponentValue"=>$contract_end_date[0]],
                ['ComponentName'=>'合同期限月2', "ComponentValue"=>$contract_end_date[1]],
                ['ComponentName'=>'合同期限日2', "ComponentValue"=>$contract_end_date[2]],
            ];
        }

        /**
         * 安徽酷驰劳动合同
         * 模版id：yDtCrUUl7uq6e3UggQaLRSAYWnzpF2JC
         * 印章id：yDCdnUU5ojca0rUy0HJMrRx07Blzgmh4
         *
         * 姓名
         * 性别
         * 联系电话
         * 证件号
         * 户籍地址
         * 合同期限年
         * 合同期限月
         * 合同期限日
         * 合同期限年2
         * 合同期限月2
         * 合同期限日2
         * 合同试用期年
         * 合同试用期月
         * 合同试用期日
         * 合同试用期年2
         * 合同试用期月2
         * 合同试用期日2
         * */
        if ($templateId == 'yDtCrUUl7uq6e3UggQaLRSAYWnzpF2JC') {
            $FormFields = [
                ['ComponentName'=>'姓名', "ComponentValue"=>$params['name']],
                ['ComponentName'=>'性别', "ComponentValue"=>$gender],
                ['ComponentName'=>'联系电话', "ComponentValue"=>$params['mobile']],
                ['ComponentName'=>'证件号', "ComponentValue"=>$params['idcard']],
                ['ComponentName'=>'户籍地址', "ComponentValue"=>$params['permanentAddress']],
                ['ComponentName'=>'合同期限年', "ComponentValue"=>$contract_start_date[0]],
                ['ComponentName'=>'合同期限月', "ComponentValue"=>$contract_start_date[1]],
                ['ComponentName'=>'合同期限日', "ComponentValue"=>$contract_start_date[2]],
                ['ComponentName'=>'合同期限年2', "ComponentValue"=>$contract_end_date[0]],
                ['ComponentName'=>'合同期限月2', "ComponentValue"=>$contract_end_date[1]],
                ['ComponentName'=>'合同期限日2', "ComponentValue"=>$contract_end_date[2]],
                ['ComponentName'=>'合同试用期年', "ComponentValue"=>$internship_start_date[0]],
                ['ComponentName'=>'合同试用期月', "ComponentValue"=>$internship_start_date[1]],
                ['ComponentName'=>'合同试用期日', "ComponentValue"=>$internship_start_date[2]],
                ['ComponentName'=>'合同试用期年2', "ComponentValue"=>$internship_end_date[0]],
                ['ComponentName'=>'合同试用期月2', "ComponentValue"=>$internship_end_date[1]],
                ['ComponentName'=>'合同试用期日2', "ComponentValue"=>$internship_end_date[2]],
            ];
            $agent = 1;
        }

        if (empty($FormFields)) {
            $this->error('合同模版id未匹配到合同表单字段！！！');
        }

        $result = false;
        Db::startTrans();
        try {

            if ($row['flowid']) {

                $txEss = new TxEss($operatorUserId, $serverSignSealId);
                if ($row['templateId'] == 'yDtCrUUl7uq6e3UggQaLRSAYWnzpF2JC') {
                    // 撤销旧合同
                    $res = $txEss->cancelContract($row['flowid'], 1, "工资查询系统后台-管理员手动重新生成合同(此合同撤销)");
                } else {
                    // 撤销旧合同
                    $res = $txEss->cancelContract($row['flowid'], 0, "工资查询系统后台-管理员手动重新生成合同(此合同撤销)");
                }

                if ($res['code']) {
                    throw new Exception('“撤销单个合同流程”出错：'.$res['msg']);
                }
            }

            // 模版发起合同-创建签署流程
            $dataArr = $params;
            $curCompanyInfo = Company::where('id', $params['company_id'])->find();
            $dataArr['company_name'] = $curCompanyInfo['name'];

            $operatorUserId = $curCompanyInfo['operatorUserId']; //经办人Id
            $serverSignSealId = $curCompanyInfo['serverSignSealId']; //企业印章Id
            $txEss = new TxEss($operatorUserId, $serverSignSealId);

            $res = $txEss->createFlow($dataArr, $agent);
            if ($res['code']) {
                throw new Exception('“模版发起合同-创建签署流程”出错：'.$res['msg']);
            }

            $flowid = $res['data']['FlowId'];

            // 模版发起合同-创建电子文档
            $res = $txEss->createTemplateDzwd($FormFields, $flowid, $templateId, $agent);
            if ($res['code']) {
                throw new Exception('“模版发起合同-创建电子文档”出错：'.$res['msg']);
            }

            // 模版发起合同-发起签署流程
            $res = $txEss->startTemplateDzwd($flowid, $agent);
            if ($res['code']) {
                throw new Exception('“模版发起合同-发起签署流程”出错：'.$res['msg']);
            }

            // 插入合同记录
            $res = ContractRecord::insert(['staff_id'=>$row['id'], 'flowid'=>$flowid, 'templateId'=>$templateId, 'createtime'=>time()]);
            if (!$res) {
                throw new Exception('“插入合同记录”出错');
            }

            // 获取H5签署链接
            $res = $txEss->getH5Link($flowid, $params, $agent);
            if ($res['code']) {
                throw new Exception('“获取H5签署链接”出错：'.$res['msg']);
            }

            $params['h5linkdata'] = serialize($res['data']);
            $params['other_data'] = isset($params['other_data']) ? serialize($params['other_data']) : serialize([]);
            $params['flowid'] = $flowid;
            $result = $this->model->where('id', $ids)->update($params);

            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    // 撤销合同
    public function cancelcontract() {
        $flowid = input('flowid');
        if (empty($flowid)) {
            $result = ['code' => 1, 'msg' => 'flowid不能为空'];
            return json($result);
        }

        $staffInfo = $this->model::where('flowid', $flowid)->find();
        if (empty($staffInfo)) {
            $result = ['code' => 1, 'msg' => 'flowid数据不存在'];
            return json($result);
        }

        $companyInfo = Company::where('id', $staffInfo['company_id'])->find();
        $operatorUserId = $companyInfo['operatorUserId']; //经办人Id
        $serverSignSealId = $companyInfo['serverSignSealId']; //企业印章Id
        $agent = 0;
        if ($companyInfo['name'] == '安徽酷驰人力资源有限公司') {
            $agent = 1;
        }

        $txEss = new TxEss($operatorUserId, $serverSignSealId);

        $res = $txEss->cancelContract($flowid, $agent, "工资查询系统后台-管理员手动撤销电子合同");
        if ($res['code']) {
            $result = ['code' => 1, 'msg' => '撤销电子合同出错：'.$res['msg']];
            return json($result);
        }

        $result = ['code' => 0, 'msg' => '撤销成功'];
        return json($result);
    }

    /**
     * 查看
     *
     * @return string|Json
     * @throws \think\Exception
     * @throws DbException
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }

        [$where, $sort, $order, $offset, $limit] = $this->buildparams();


        $list = $this->model
            ->where($where)
            ->order($sort, $order)
            ->paginate($limit);

        $total = $list->total();
        $rows = $list->items();
        if ($rows) {

            // 查询公司列表
            $companyList = Company::where('id', '>', 0)->select();
            if ($companyList) {
                $companyList = formatkey($companyList, 'id');
            }

            foreach ($rows as $key => $list) {
                $rows[$key]['company_name'] = isset($companyList[$list['company_id']]) ? $companyList[$list['company_id']]['name'] : '';
            }
        }

        $result = ['total' => $total, 'rows' => $rows];
        return json($result);
    }

    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if (!preg_match("/^1\d{10}$/", $params['mobile'])) {
            $this->error('手机号不合法');
        }

        // 验证身份证
        if (!checkIdCard($params['idcard'])) {
            $this->error('身份证号不合法');
        }

        $exists = $this->model->where('mobile', $params['mobile'])->find();
        if ($exists) {
            $this->error('手机号'.$exists['mobile'].'已存在，不能添加重复的手机号数据');
        }

        $exists = $this->model->where('idcard', $params['idcard'])->find();
        if ($exists) {
            $this->error('身份证号'.$exists['idcard'].'已存在，不能添加重复的身份证号数据');
        }

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $result = $this->model->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if (!preg_match("/^1\d{10}$/", $params['mobile'])) {
            $this->error('手机号不合法');
        }

        // 验证身份证
        if (!checkIdCard($params['idcard'])) {
            $this->error('身份证号不合法');
        }

        $exists = $this->model::where(['mobile'=>$params['mobile'], 'id'=>['<>', $ids]])->find();
        if (!empty($exists)) {
            $this->error('手机号'.$params['mobile'].'已存在，不能添加重复的手机号数据');
        }

        $exists = $this->model::where(['idcard'=>$params['idcard'], 'id'=>['<>', $ids]])->find();
        if (!empty($exists)) {
            $this->error('身份证号'.$params['idcard'].'已存在，不能添加重复的身份证号数据');
        }

        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    /**
     * 还原
     *
     * @param $ids
     * @return void
     */
    public function restore($ids = null)
    {
        if (false === $this->request->isPost()) {
            $this->error(__('Invalid parameters'));
        }
        $ids = $ids ?: $this->request->post('ids');
        $pk = $this->model->getPk();
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        if ($ids) {
            $this->model->where($pk, 'in', $ids);
        }
        $count = 0;
        Db::startTrans();
        try {
            $list = $this->model->onlyTrashed()->select();
            foreach ($list as $item) {
                $exists = $this->model->where('mobile', $item['mobile'])->find();
                if ($exists) {
                    $this->error('手机号'.$exists['mobile'].'已存在，不能恢复重复的手机号数据');
                }

                $exists = $this->model->where('idcard', $item['idcard'])->find();
                if ($exists) {
                    $this->error('身份证号'.$exists['idcard'].'已存在，不能恢复重复的身份证号数据');
                }

                $count += $item->restore();
            }
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        }
        $this->error(__('No rows were updated'));
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


}
